<html>
<head>

<title>Groovy Goodness: Find First Non-Null Result From a Closure</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Find First Non-Null Result From a Closure</h3>

<div class="post">
<p>A new feature from Groovy 1.8 (according to the Javadoc it is available since 1.8) is already available in Groovy 1.7.5. With the method <code>findResult()</code> we iterate through an object and find the first non-null result from a closure. We can even define a default value if there is no non-null result.</p>
<pre class="brush:groovy">
def list = ['Groovy', 'Griffon', 'Grails', 'Gradle']

assert list.findResult { it.startsWith('Gra') ? it : null } == 'Grails'
assert list.findResult('Gr8') { 
    if (it.size() < 6) {
        "found text with size smaller than 6"
    }
} == 'Gr8'
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>